package com.cloudkinto.service.mail.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.cloudkinto.common.RedisKeyConstants;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.utils.dict.StaticDict;
import com.cloudkinto.dto.mail.MailAccountDto;
import com.cloudkinto.entity.MailAccountDo;
import com.cloudkinto.dao.MailAccountDao;
import com.cloudkinto.entity.PlatformStoreDo;
import com.cloudkinto.service.mail.MailAccountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;

import com.cloudkinto.service.mail.MailService;
import com.cloudkinto.service.mail.vo.MailAccountAddReq;
import com.cloudkinto.service.mail.vo.MailAccountUpdateReq;
import com.cloudkinto.service.platform.PlatformStoreService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.*;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  service实现类
 * </p>
 * @author hua
 * @since 2025-01-10
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class MailAccountServiceImpl extends ServiceImpl<MailAccountDao, MailAccountDo> implements MailAccountService {
    @Autowired
    private MailAccountDao dao;
    @Autowired
    private MailService mailService;
    @Autowired
    private PlatformStoreService platformStoreService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${gbc.customer}")
    private String customer;


    //做新增之前要执行的业务定制处理
    private void handlerAddBefore(MailAccountDo entityDo, Long userId) {
        entityDo.setCreateBy(userId);
        entityDo.setCreateTime(new Date());
        entityDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
    }

    @Override
    public SingleResult updateInit(Long id) {
        return SingleResult.success("");
    }

    @Override
    public void update(MailAccountUpdateReq req, Long userId, Long companyId) {
        MailAccountDo entityDo = dao.selectById(req.getId());
        if (entityDo == null) {
            throw new BizException(SysConstant.No_Data);
        }
        boolean storeNullFlag = entityDo.getStoreId() != null;
        if (StringUtils.isNotBlank(entityDo.getSmtp())) {
            //乐天
            this.checkMailPassword(entityDo.getUser(), req.getPassword(), entityDo.getSmtp(), entityDo.getPort());
        }
        else {
            try {
                Store store = mailService.getIMAPStore(entityDo.getSmtp(), entityDo.getImap(), entityDo.getUser(), req.getPassword());
                store.close();
            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new BizException(SysConstant.Mail_Password_Error);
            }
        }
        entityDo.setStoreId(req.getStoreId());
        entityDo.setPassword(req.getPassword());
        entityDo.setDefaultConfirmTemplateId(req.getDefaultConfirmTemplateId());
        entityDo.setDefaultSendTemplateId(req.getDefaultSendTemplateId());
        entityDo.setIsAutoSent(req.getIsAutoSent());
        entityDo.setEmailTitleType(req.getEmailTitleType());
        entityDo.setUser(req.getUser());
        entityDo.setStatus("normal");
        if(req.getTailContent()!=null)
        {
            entityDo.setTailContent(req.getTailContent());
        }
        if(req.getHeadContent()!=null)
        {
            entityDo.setHeadContent(req.getHeadContent());
        }
        entityDo.setTitle(req.getTitle());
        dao.updateById(entityDo);

        if (storeNullFlag && req.getStoreId() == null) {
            LambdaUpdateWrapper<MailAccountDo> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(MailAccountDo::getId, req.getId());
            updateWrapper.set(MailAccountDo::getStoreId, null);
            this.update(updateWrapper);
        }
        String mailAccountStoreRedisKey = RedisKeyConstants.MailAccountStoreKey + customer + "_" +companyId;
        redisTemplate.delete(mailAccountStoreRedisKey);
    }

    public void checkMailPassword(String mailNo, String password, String smtp, String port) {
        Properties props = mailService.getSmtpProperties(smtp, mailNo, password, port);
        Authenticator authenticator = mailService.getAuthenticator(props);
        Session mailSession = Session.getInstance(props, authenticator);
        try {
            Transport transport = mailSession.getTransport();
            transport.connect();
            transport.close();
        } catch (MessagingException e) {
            e.printStackTrace();
            throw new BizException("授权失败,请确认回信邮箱账号密码");
        }//javax.mail.AuthenticationFailedException: 535 5.7.0 ...authentication rejected

    }


    @Override
    public int delete(Long id, Long userId) {
        MailAccountDo entityDo = dao.selectById(id);
        handlerDeleteBefore(entityDo, userId);
        dao.updateById(entityDo);
        return dao.deleteById(id);
    }

    //做删除之前要执行的业务定制处理
    private void handlerDeleteBefore(MailAccountDo entityDo, Long userId) {
        entityDo.setDeleteBy(userId);
        entityDo.setDeleteTime(new Date());
    }

    @Override
    public Object detail(Long id) {
        MailAccountDo entityDo =  dao.selectById(id);
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return handlerDetailAfter(res);
    }

    //查询明细之后要执行的业务定制处理
    private Object handlerDetailAfter(Object res) {
        return res;
    }

    @Override
    public SingleResult pageInit(Long companyId) {
        Map<String, Object> result = new HashMap<>();
        result.put("storeList", platformStoreService.getList(companyId));
        return SingleResult.success(result);
    }


    @Override
    public PageResult getListPage(Map<String, Object> map) {
        IPage<MailAccountDto> page = pageInit(map);
        page = dao.getList(page, map);
        PageResult result = new PageResult(page.getRecords(), (int)page.getCurrent(), (int)page.getSize(), (int)page.getTotal(), (int)page.getPages());
        return result;
    }

    //查询分页列表之后对列表数据的处理
    private List<Object> handlerListAfter(List<MailAccountDo> list ){
        List<Object> result = new ArrayList<>();
        return result;
    }

    private IPage<MailAccountDto> pageInit(Map<String, Object> map) {
        IPage<MailAccountDto> page = new Page();
        page.setSize(map.get("pageSize") != null ? Long.parseLong(map.get("pageSize").toString()) : 10);
        page.setCurrent(map.get("current") != null ? Long.parseLong(map.get("current").toString()) : 1);
        return page;
    }

    private QueryWrapper<MailAccountDo> queryBuild(Map<String, String> map) {
        QueryWrapper<MailAccountDo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(map.get("keyword"))) {
            wrapper.like("keyword", map.get("keyword"));
        }
        return wrapper;
    }



    @Override
    public void add(MailAccountAddReq req, Long userId, Long companyId) {
        //验证邮箱格式
        if (req.getMailNo().matches("/^[A-Za-z\\d]+([-_.][A-Za-z\\d]+)*@([A-Za-z\\d]+[-.]){1,2}[A-Za-z\\d]{2,5}$/g")) {
            throw new BizException(SysConstant.Mail_Format_Error);
        }
        MailAccountDo accountDo = dao.selectOne(new LambdaQueryWrapper<MailAccountDo>()
                .eq(MailAccountDo::getMailNo, req.getMailNo())
                .last(" limit 1"));
        if (accountDo != null) {
            throw new BizException(SysConstant.Mail_Account_Exist);
        }
        boolean flag = false;
        if (StringUtils.isBlank(req.getSmtp())) {
            String type = req.getMailNo().substring(req.getMailNo().indexOf("@"));
            for (StaticDict.Mail_Type mailType : StaticDict.Mail_Type.values()) {
                if (type.equals(mailType.getValue())) {
                    req.setSmtp(mailType.getSmtp());
                    req.setImap(mailType.getImap());
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                throw new BizException(SysConstant.Mail_Account_Smtp_Type);
            }
        }

        if (StringUtils.isNotBlank(req.getSmtp())) {
            //乐天
            this.checkMailPassword(req.getMailNo(), req.getPassword(), req.getSmtp(), req.getPort());
        } else {
            try {
                Store store = mailService.getIMAPStore(req.getSmtp(), req.getImap(), req.getMailNo(), req.getPassword());
                store.close();
            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new BizException(SysConstant.Mail_Account_Password_Smtp_Type);
            }
        }
        MailAccountDo entityDo = new MailAccountDo();
        BeanUtils.copyProperties(req, entityDo);
        entityDo.setSmtp(req.getSmtp());
        entityDo.setStatus("normal");
        handlerAddBefore(entityDo, userId);
        dao.insert(entityDo);

        String mailAccountStoreRedisKey = RedisKeyConstants.MailAccountStoreKey + customer + "_" +companyId;
        redisTemplate.delete(mailAccountStoreRedisKey);
    }

}
